import json
import os

BILLS_FILE_PATH = "data/billing_history.json"
MEMBERS_FILE_PATH = "data/members.json"

def load_billing_history_from_file():
    """从文件加载历史账单"""
    try:
        if os.path.exists(BILLS_FILE_PATH):
            with open(BILLS_FILE_PATH, 'r', encoding='utf-8') as file:
                return json.load(file)
    except (json.JSONDecodeError, FileNotFoundError):
        pass
    return []

def save_bill_to_file(bill_object):
    """保存账单到文件"""
    # 确保数据目录存在
    os.makedirs(os.path.dirname(BILLS_FILE_PATH), exist_ok=True)
    
    # 加载现有账单
    bills = load_billing_history_from_file()
    
    # 添加新账单
    bills.append(bill_object)
    
    # 保存回文件
    with open(BILLS_FILE_PATH, 'w', encoding='utf-8') as file:
        json.dump(bills, file, indent=4, ensure_ascii=False)

def load_member_data_from_file():
    """从文件加载成员数据"""
    try:
        if os.path.exists(MEMBERS_FILE_PATH):
            with open(MEMBERS_FILE_PATH, 'r', encoding='utf-8') as file:
                return json.load(file)
    except (json.JSONDecodeError, FileNotFoundError):
        pass
    return []

def save_member_data_to_file(member_list):
    """保存成员数据到文件"""
    # 确保数据目录存在
    os.makedirs(os.path.dirname(MEMBERS_FILE_PATH), exist_ok=True)
    
    with open(MEMBERS_FILE_PATH, 'w', encoding='utf-8') as file:
        json.dump(member_list, file, indent=4, ensure_ascii=False)

def view_historical_bills_interaction():
    """查看历史账单的交互函数"""
    bills = load_billing_history_from_file()
    
    if not bills:
        print("暂无历史账单")
        return
    
    # 显示最近的3条账单
    recent_bills = bills[-3:] if len(bills) > 3 else bills
    
    print(f"\n===== 历史账单 ({len(recent_bills)}条最近记录) =====")
    
    for i, bill in enumerate(reversed(recent_bills), 1):
        billing_date = bill.get("billing_date", "未知日期")
        total_electricity = bill.get("total_electricity_cost", 0)
        total_water = bill.get("total_water_cost", 0)
        total_cost = total_electricity + total_water
        
        print(f"\n账单 #{len(bills) - len(recent_bills) + i} ({billing_date})")
        print(f"总电费: {total_electricity:.2f} 元")
        print(f"总水费: {total_water:.2f} 元")
        print(f"总费用: {total_cost:.2f} 元")
        print("成员分摊:")
        
        for member in bill.get("members_share", []):
            name = member.get("name", "未知")
            total_share = member.get("total_share", 0)
            print(f"  - {name}: {total_share:.2f} 元")
    
    print("\n如需查看完整历史记录，请直接查看 data/billing_history.json 文件")    